import {
	defineStore
} from 'pinia';
import http from '@/common/request';
import useChatStore from './chatStore.js'

export default defineStore('groupStore', {
	state: () => {
		return {
			groups: [],
			activeIndex: -1
		}
	},
	actions: {
		setGroups(groups) {
			this.groups = groups;
		},
		activeGroup(index) {
			this.activeIndex = index;
		},
		addGroup(group) {
			this.groups.unshift(group);
		},
		removeGroup(groupId) {
			this.groups.filter(g => g != null).forEach((g, index) => {
				if (g.id == groupId) {
					this.groups.splice(index, 1);
					if (this.activeIndex >= this.groups.length) {
						this.activeIndex = this.groups.length - 1;
					}
				}
			})
		},
		updateGroup(group) {
			let g = this.findGroup(group.id);
			if (g) {
				Object.assign(g, group);
			}
		},
		clear() {
			this.groups = [];
			this.activeGroup = -1;
		},
		loadGroup() {
			return new Promise((resolve, reject) => {
				http({
					url: '/group/list',
					method: 'GET'
				}).then((groups) => {
					groups.forEach(i => {
						if (i.groupNumber != null) {
							i.groupNumber = this.padNumber(i.groupNumber)
						}
					})
					this.setGroups(groups);
					resolve();
				}).catch((res) => {
					reject(res);
				})
			});
		},
		padNumber(number) {
			return number.toString().padStart(6, '0');
		}
	},
	getters: {
		findGroup: (state) => (id) => {
			 // 添加可选链操作符（或显式空值检查）
			return state.groups.find((g) => g?.id == id); 
		},
		privateGroup: (state) => () => {
			return state.groups.filter(e => [0, 2].includes(e.groupType))
		},
		businessGroup: (state) => () => {
			return state.groups.filter(e => 1 == e.groupType)
		},
	}
})